package com.changjie.wang.doc;

import com.changjie.wang.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class EsClient_CreateDoc {
    /**
     * 插入文档数据
     * @param args
     */
    public static void main(String[] args) {
        //创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );
        try {
            User user = new User();
            user.setName("王昌杰");
            user.setSex("男");
            user.setAge(24);
            //想要向ES插入数据，就必须把数据转换为JSON格式
            ObjectMapper objectMapper = new ObjectMapper();
            String userJson = objectMapper.writeValueAsString(user);

            //插入数据
            IndexRequest request = new IndexRequest();
            request.index("user").id("001");
            //指定内容类型
            request.source(userJson, XContentType.JSON);
            //发送创建文档请求
            IndexResponse response = esClient.index(request,RequestOptions.DEFAULT);
            System.out.println(response.getResult());
            System.out.println(response.getIndex());

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //关闭ES客户端
            try {
                esClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
